package pl.edu.pw.ee.buildcity.notifiers;

import org.apache.commons.lang.time.DateUtils;
import org.fest.assertions.Assertions;
import org.fest.assertions.Fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pl.edu.pw.ee.buildcity.domain.BuildStatus;
import pl.edu.pw.ee.buildcity.entities.BuildActivity;
import pl.edu.pw.ee.buildcity.entities.BuildDefinition;
import pl.edu.pw.ee.buildcity.entities.SCMCommit;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author Mateusz
 * @since 2010-02-14
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:mail-notifier-context.xml"})
public class MailNotifierIntegrationTestCase {

	@Resource(name = "mailNotifier")
	private MailNotifier mailNotifier;

	@Test
	public void shouldSendMailWithBuildResult() {
		//Given
		List<String> recipients = Arrays.asList("mateusz.grzechocinski@gmail.com");

		BuildDefinition buildDefinition = new BuildDefinition().withName("My Build");

		Date started = DateUtils.addSeconds(new Date(), -12);

		BuildActivity buildActivity = new BuildActivity().started(started).ended(new Date());
		buildActivity.setResult(BuildStatus.FAILED);
		buildActivity.setBuildDefinition(buildDefinition);
		buildActivity.setBuildNumber(new Random().nextInt(100));

		SCMCommit scmCommit1 = new SCMCommit().byAuthor("mgrzechocinski").onDate(new Date()).withChanges("myFile1");
		SCMCommit scmCommit2 = new SCMCommit().byAuthor("mgrzechocinski2").onDate(new Date()).withChanges("myFile2");
		buildActivity.setCommits(Arrays.asList(scmCommit1, scmCommit2));

		//When
		mailNotifier.notifyEndOfBuild(recipients, buildActivity);

		//Then
		//Should receive email ;)
	}

	@Test
	public void shouldThrowExceptionWhenEmailIsInvalid() {
		//Given
		List<String> recipients = Arrays.asList("wrongEmail");

		BuildDefinition buildDefinition = new BuildDefinition().withName("My Build");

		BuildActivity buildActivity = new BuildActivity().ended(new Date());

		buildActivity.setResult(BuildStatus.FAILED);
		buildActivity.setBuildDefinition(buildDefinition);
		buildActivity.setBuildNumber(new Random().nextInt(100));

		//When
		try {
			mailNotifier.notifyEndOfBuild(recipients, buildActivity);
			Fail.fail("Exception should be throws as email is invalid and email couldn't be sent");
		} catch (Exception e) {
			//Then
			Assertions.assertThat(e).isInstanceOf(CouldNotNotifyException.class);
			Assertions.assertThat(e.getMessage()).startsWith("Could not send message to recipient 'wrongEmail' due to exception:");
		}
	}
}